/**
 * 
 */
package com.sc.softmgr.business.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.acc.softmgr.model.SoftmgrProject;
import com.acc.softmgr.model.SoftmgrSystem;
import com.acc.softmgr.model.SoftmgrSystemExample;
import com.acc.softmgr.model.SysUser;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sc.softmgr.business.service.ISoftmgetProjectFeignService;
import com.sc.softmgr.business.service.ISoftmgrSystemService;
import com.sc.softmgr.common.constant.DeleteStatus;
import com.sc.softmgr.common.constant.enums.RestStatus;
import com.sc.softmgr.common.utils.date.DateBase;
import com.sc.softmgr.common.web.DataGridObject;

/**
 * 
 * @content
 * 
 * @date 2017年5月8日
 * 
 * @author OprCalf
 * 
 */
@Controller
@RequestMapping("softSystem")
public class SoftmgrSystemController {

	private static Map<Integer, String> map = new HashMap<Integer, String>();

	@Autowired
	private ISoftmgetProjectFeignService softmgetProjectFeignService;

	@Autowired
	private ISoftmgrSystemService softmgrSystemService;

	@RequestMapping(value = "toSoftSystem", method = RequestMethod.GET)
	public String toSoftSystem() {
		return "softSystem/softSystem";
	}

	/**
	 * 查询列表页
	 * 
	 * @param project_name
	 * @param project_english
	 * @param page
	 * @param rows
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "searchSoftSystem", method = RequestMethod.GET)
	@ResponseBody
	public DataGridObject<SoftmgrSystem> searchSoftSystem(
			@RequestParam(value = "project_id", required = false) String project_id, SoftmgrSystem softmgrSystem,
			@RequestParam Integer page, @RequestParam Integer rows) throws Exception {
		DataGridObject<SoftmgrSystem> responseObject = new DataGridObject<SoftmgrSystem>();
		SoftmgrSystemExample example = new SoftmgrSystemExample();
		if (!StringUtils.isEmpty(project_id)) {
			example.getCriteria().andProject_idEqualTo(Integer.valueOf(project_id));
		}
		if (!StringUtils.isEmpty(softmgrSystem.getSystem_name())) {
			example.getCriteria().andSystem_nameLike("%" + softmgrSystem.getSystem_name() + "%");
		}
		if (!StringUtils.isEmpty(softmgrSystem.getSystem_english())) {
			example.getCriteria().andSystem_englishLike("%" + softmgrSystem.getSystem_english() + "%");
		}
		if (page == null || page == 0) {
			page = 1;
		}

		example.getCriteria().andDeletedEqualTo(DeleteStatus.FALSE);
		example.setCount(page * rows);
		example.setLimitStart((page - 1) * rows);

		List<SoftmgrSystem> softmgrSystems = softmgrSystemService.selectByExample(example);
		for (SoftmgrSystem ss : softmgrSystems) {
			ss.setCreateTimestring(DateBase.formatDate(ss.getCreatetime(), DateBase.DATE_PATTERN_DATETIME));
			ss.setProjectName(cacheProjectName(ss.getProject_id()));
		}
		responseObject.setTotal(page * rows);
		responseObject.setRows(softmgrSystems);
		return responseObject;
	}

	/**
	 * 新增项目
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/addSoftSystem", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject addSoftSystem(@RequestParam String project_id, SoftmgrSystem softmgrSystem,
			HttpServletRequest request) throws Exception {
		JSONObject json = new JSONObject();
		SysUser currentUser = (SysUser) request.getSession().getAttribute("currentUser");
		if (StringUtils.isEmpty(project_id) || StringUtils.isEmpty(softmgrSystem.getSystem_name())
				|| StringUtils.isEmpty(softmgrSystem.getSystem_english())) {
			json.put("status", RestStatus.PARAMETER_REQUIRED.code);
			json.put("message", RestStatus.PARAMETER_REQUIRED.message);
			return json;
		} else {
			// ----------判断唯一性------------
			boolean exitSystem = exitSoftmgrSystem(project_id, softmgrSystem.getSystem_name(),
					softmgrSystem.getSystem_english());
			if (exitSystem) {
				json.put("status", RestStatus.NOT_UNIQUE.code);
				json.put("message", RestStatus.NOT_UNIQUE.message);
				return json;
			} else {
				SoftmgrSystem ss = new SoftmgrSystem();
				ss.setCreatetime(new Date());
				ss.setCreateby(currentUser.getUsername());
				ss.setProject_id(Integer.valueOf(project_id));
				ss.setSystem_name(softmgrSystem.getSystem_name());
				ss.setSystem_english(softmgrSystem.getSystem_english());
				ss.setDeleted(DeleteStatus.FALSE);
				softmgrSystemService.insert(ss);
				json.put("status", RestStatus.SUCCESS.code);
				json.put("message", RestStatus.SUCCESS.message);
				return json;
			}
		}
	}

	/**
	 * 修改用户
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "editSoftSystem", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject editSoftSystem(@RequestParam String project_id, SoftmgrSystem softmgrSystem,
			HttpServletRequest request) throws Exception {
		JSONObject json = new JSONObject();
		SysUser currentUser = (SysUser) request.getSession().getAttribute("currentUser");
		if (StringUtils.isEmpty(project_id) || StringUtils.isEmpty(softmgrSystem.getSystem_name())
				|| StringUtils.isEmpty(softmgrSystem.getSystem_english()) || softmgrSystem.getId() == null
				|| softmgrSystem.getId() == 0) {
			json.put("status", RestStatus.PARAMETER_REQUIRED.code);
			json.put("message", RestStatus.PARAMETER_REQUIRED.message);
			return json;
		} else {
			// ----------判断唯一性------------
			SoftmgrSystem ss = softmgrSystemService.selectByPrimaryKey(softmgrSystem.getId());
			boolean exitSystem = exitSoftmgrSystem(project_id, softmgrSystem.getSystem_name(),
					softmgrSystem.getSystem_english());
			if (exitSystem) {
				json.put("status", RestStatus.NOT_UNIQUE.code);
				json.put("message", RestStatus.NOT_UNIQUE.message);
				return json;
			} else {
				ss.setProject_id(Integer.valueOf(project_id));
				ss.setSystem_name(softmgrSystem.getSystem_name());
				ss.setSystem_english(softmgrSystem.getSystem_english());
				ss.setUpdateby(currentUser.getUsername());
				ss.setUpdatetime(new Date());
				softmgrSystemService.updateByPrimaryKey(ss);
				json.put("status", RestStatus.SUCCESS.code);
				json.put("message", RestStatus.SUCCESS.message);
				return json;
			}
		}
	}

	/**
	 * 查询详情
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/{id}/searchSoftSystem", method = RequestMethod.GET)
	@ResponseBody
	public JSONObject searchUser(@PathVariable Integer id) throws Exception {
		JSONObject json = new JSONObject();
		if (id == null || id == 0) {
			json.put("status", RestStatus.PARAMETER_REQUIRED.code);
			json.put("message", RestStatus.PARAMETER_REQUIRED.message);
			return json;
		}
		SoftmgrSystem SoftmgrSystem = softmgrSystemService.selectByPrimaryKey(id);
		json.put("status", RestStatus.SUCCESS.code);
		json.put("message", RestStatus.SUCCESS.message);
		json.put("data", SoftmgrSystem);
		return json;
	}

	/**
	 * 删除项目
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/removeSoftSystem", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject removeSoftSystem(@RequestParam Integer id) throws Exception {
		JSONObject json = new JSONObject();
		if (id == null || id == 0) {
			json.put("status", RestStatus.PARAMETER_REQUIRED.code);
			json.put("message", RestStatus.PARAMETER_REQUIRED.message);
			return json;
		}
		SoftmgrSystem softmgrSystem = softmgrSystemService.selectByPrimaryKey(id);
		softmgrSystem.setDeleted(DeleteStatus.TRUE);
		softmgrSystemService.updateByPrimaryKey(softmgrSystem);
		json.put("status", RestStatus.SUCCESS.code);
		json.put("message", RestStatus.SUCCESS.message);
		return json;
	}

	/**
	 * 获取指定Project下面的system
	 * 
	 * @param projectId
	 * @return
	 */
	@RequestMapping(value = "getSoftSystems/{projectId}", method = RequestMethod.GET)
	@ResponseBody
	public String getSoftSystems(@PathVariable Integer projectId) throws Exception {
		SoftmgrSystemExample example = new SoftmgrSystemExample();
		example.getCriteria().andProject_idEqualTo(projectId);
		example.getCriteria().andDeletedEqualTo(DeleteStatus.FALSE);
		List<SoftmgrSystem> list = softmgrSystemService.selectByExample(example);
		JSONArray jsonArray = new JSONArray();
		for (SoftmgrSystem system : list) {
			JSONObject json = new JSONObject();
			json.put("id", system.getId());
			json.put("text", system.getSystem_name());
			jsonArray.add(json);
		}
		return jsonArray.toJSONString();
	}

	private boolean exitSoftmgrSystem(String projectId, String systemName, String systemEnglish) {
		SoftmgrSystemExample example = new SoftmgrSystemExample();
		example.getCriteria().andProject_idEqualTo(Integer.valueOf(projectId));
		example.getCriteria().andSystem_nameEqualTo(systemName);
		example.getCriteria().andSystem_englishEqualTo(systemEnglish);
		example.getCriteria().andDeletedEqualTo(DeleteStatus.FALSE);
		List<SoftmgrSystem> softmgrSystems = softmgrSystemService.selectByExample(example);
		if (softmgrSystems != null && softmgrSystems.size() > 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 缓存所有的projectName,让时间复杂度控制在project数量上 避免每次都要去连接拿取
	 * 二期更改为redis缓存,这样在做分布式的时候,可以避免缓存不同步问题
	 * 
	 * @return
	 */
	private String cacheProjectName(Integer projectId) {
		String projectName = map.get(projectId);
		if (StringUtils.isEmpty(projectName)) {
			JSONObject json = softmgetProjectFeignService.searchSoftProject(projectId);
			if (!"500".equals(json.get("status"))) {
				SoftmgrProject softmgrProject = json.getObject("data", SoftmgrProject.class);
				map.put(projectId, softmgrProject.getProject_name());
				projectName = map.get(projectId);
			}
		}
		return projectName;
	}

}
